/**
 * Created by zhulizhe on 2017/8/28.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    ScrollView,
    Button,
    StyleSheet,
    Platform,
    DeviceEventEmitter
} from 'react-native';
import {observable, action, computed, observe} from 'mobx'
import {observer} from 'mobx-react/native'
import Constant from "../Contant";
import SearchBox from "../component/SearchBox";
import Ionicons from 'react-native-vector-icons/Ionicons';
import addressMgrStore from '../store/AddrMgrStore'

// 搜索框
const SearchBar = observer(({navigation}) => {
    return <View style={{marginHorizontal: 10, marginVertical: 5, flexDirection: 'row', alignItems: 'center'}}>
        <View style={styles.city}>
            <TouchableOpacity onPress={() => {
                navigation.navigate('CityChooser') ;
            }}>
                <Text>{addressMgrStore.mapAuto.city}</Text>
            </TouchableOpacity>
        </View>
        <View style={{flexGrow: 7}}>
            <SearchBox
                placeholder="搜索地址"
                onClick={()=>{
                    navigation.navigate('SearchAddress')
                }}/>
        </View>
    </View>
})

export const SectionHeader = ({title}) => {
    return <View style={{paddingHorizontal: 15, paddingVertical: 10}}>
        <Text style={{color: Constant.TEXT_COLOR_6}}>{title}</Text>
    </View>
}


export const Label = ({title})=>{
    return <View style={{
        borderWidth:StyleSheet.hairlineWidth,
        borderColor:Constant.BLUECOLOR,
        paddingVertical:2,
        paddingHorizontal:10,
        borderRadius:2
    }}>
        <Text style={{fontSize:13,color:Constant.BLUECOLOR}}>{title}</Text>
    </View>
}

export const DeliveryAddressCell = ({address,onPress})=>{
    return <TouchableOpacity style={[{paddingVertical:5,paddingHorizontal:15,backgroundColor:'#fff'},styles.borderBottom]} onPress={()=>{onPress(address)}}>
        <View style={{flexDirection:'row',alignItems:'center',paddingVertical:5}}>
            {
                address.addressTagName?(<View style={{paddingRight:10}}>
                    <Label title={address.addressTagName}/>
                </View>) : null
            }
            <Text>{address.name}</Text>
            <View style={{paddingHorizontal:15}}>
                <Text>{address.phoneNum}</Text>
            </View>
        </View>
        <View style={{flexDirection:'row',alignItems:'center',overflow:'hidden'}}>
            <Text style={styles.textSmall}>{address.address.mapAddress}</Text>
            <View style={{paddingHorizontal:15}}>
                <Text style={styles.textSmall}>{address.address.appendingAddress}</Text>
            </View>
        </View>
    </TouchableOpacity>
}

// 用户收货地址列表
const UserAddress = observer(({onPress})=>{
    return <View>
        <SectionHeader title="收货地址"/>
        {
            addressMgrStore.deliveryAddressListMgr.list.map((m,index)=><DeliveryAddressCell key={index} address={m} onPress={onPress}/>)
        }
    </View>
})

// 当前位置
const CurrentAddress = observer(({onPress}) => {
    return <View>
        <SectionHeader title="当前位置"/>
        <View style={{
            flexDirection: 'row',
            alignItems: 'center',
            backgroundColor: '#fff'
        }}>
            <View
                style={{flex: 7}}>
                <AddrItem
                    onPress={onPress}
                    title={addressMgrStore.mapAuto.currentAddress.mappingAddress}/>
            </View>
            <View style={{ paddingHorizontal: 10}}>
                <TouchableOpacity
                    onPress={() => {
                        addressMgrStore.refreshMyLocation();
                    }}>
                    <View style={{flexDirection: 'row', alignItems: 'center'}}>
                        <Ionicons name="ios-locate-outline" size={18} color={Constant.BLUECOLOR}/>
                        <Text style={{
                            paddingHorizontal: 5,
                            color: Constant.BLUECOLOR
                        }}>重新定位</Text>
                    </View>
                </TouchableOpacity>
            </View>
        </View>
    </View>
})

const NearByAddress = observer(({onPress}) => {
    return <View>
        <SectionHeader title="附近地址"/>
        {
            addressMgrStore.mapAuto.neighborList.map((poi, index) => {
                return <AddrItem
                    key={index}
                    poi={poi}
                    onPress={() => {
                        onPress(poi);
                    }}/>
            })
        }
    </View>
})

const AddrItem = ({poi = {address: ''}, onPress, title = null}) => {
    return <TouchableOpacity
        onPress={onPress}
        activeOpacity={0.75}
        style={[{
            padding: 15,
            backgroundColor: '#fff'
        }, styles.borderBottom]}>
        <Text>{title ? title : poi.name}</Text>
    </TouchableOpacity>
}

// 收货地址
export default class DeliveryAddress extends Component {

    static navigationOptions = ({navigation}) => ({
        title: '收货地址',
        headerRight: (
            <TouchableOpacity
                style={{padding:10}}
                onPress={() => {
                    //navigation.navigate('AddOrEditAddress',{editAddress:null})
                    navigation.navigate('Map',{position:{latitude:addressMgrStore.activeAddress.latitude,longitude:addressMgrStore.activeAddress.longitude}})
                }}
            >
                <Image style={{height:20,width:20,resizeMode:'contain'}} source={require('../../luoasserts/homeLuo/nav_btn_location.png')}></Image>
            </TouchableOpacity>

        ),
    })

    // 更新ActiveAddr
    updateActiveAddr(poi, convert = null) {
        if (convert) {
            addressMgrStore.setSelected(convert(poi));
        }
        else {
            addressMgrStore.setSelected(poi);
        }
        this.props.navigation.goBack();
    }


    render() {
        return <ScrollView style={{
            flex: 1,
            backgroundColor: Constant.GRAYBGCOLOR
        }}>
            <SearchBar
                navigation={this.props.navigation}/>
            <UserDeliveryAddress navigation={this.props.navigation} onPress={(poi) => {
                LOG('收货地址选择---------'+JSON.stringify(poi));
                this.updateActiveAddr(poi, addressMgrStore.mapAuto.convertPOI2Address);
            }}/>
            <CurrentAddress
                onPress={() => {
                    let currentAddress = addressMgrStore.mapAuto.currentAddress;
                    this.updateActiveAddr(currentAddress);
                }}/>
            {/*<UserAddress onPress={(poi) => {*/}
                {/*LOG('选择收货地址----------'+JSON.stringify(poi));*/}
                {/*this.updateActiveAddr(poi, addressMgrStore.mapAuto.convertPOI2Address);*/}
            {/*}}/>*/}
            <NearByAddress
                onPress={(poi) => {
                    this.updateActiveAddr(poi, addressMgrStore.mapAuto.convertPOI2Address);
                }}/>
        </ScrollView>
    }
    componentDidMount(){
        this.addrChangeListener = DeviceEventEmitter.addListener(Constant.CURRENTLOCATIONCHANGE, (poi) => {
            this.props.navigation.goBack();
        });
    }
    componentWillUnmount() {
        if(this.addrChangeListener!=null){
            this.addrChangeListener.remove();
        }
    }
}
@observer
class UserDeliveryAddress extends Component{
    render(){
        let {navigation,onPress} = this.props;
        let homeAddress=null;
        let companyAddress=null;
        let otherAddress=null;
        addressMgrStore.deliveryList.forEach((address)=>{
              if(address.addressTagName=='家庭'){
                  homeAddress=address;
              }else if(address.addressTagName=='单位'){
                  companyAddress=address;
              }else if(address.addressTagName==''){

            }
        });
        return <View style={{flexDirection:'row',backgroundColor:'white',padding:10}}>

            <TouchableOpacity style={{alignItems:'center',flex:1}} activeOpacity={0.9} onPress={()=>{
                homeAddress==null?navigation.navigate('AddOrEditAddress',{editAddress:null}):onPress(homeAddress);
            }
            }>
                <Text style={{color:'black'}}>家庭</Text>
                <Text style={{fontSize:12,marginTop:5}} numberOfLines={1}>{homeAddress==null?'设置家庭地址':homeAddress.address.fullAddress}</Text>
            </TouchableOpacity>
            <TouchableOpacity style={{alignItems:'center',flex:1}} activeOpacity={0.9} onPress={
                ()=>{
                    companyAddress==null?navigation.navigate('AddOrEditAddress',{editAddress:null}):onPress(companyAddress);
                }
            }>
                <Text style={{color:'black'}}>单位</Text>
                <Text style={{fontSize:12,marginTop:5}} numberOfLines={1}>{companyAddress==null?'设置单位地址':companyAddress.address.fullAddress}</Text>
            </TouchableOpacity>
            <TouchableOpacity style={{alignItems:'center',flex:1}} activeOpacity={0.9} onPress={
                ()=>{

                }}
            >
                <Text style={{color:'black'}}>其他</Text>
                <Text style={{fontSize:12,marginTop:5}} numberOfLines={1}>设置其他地址</Text>
            </TouchableOpacity>
        </View>
    }
}
const styles = {
    borderBottom: {
        borderBottomColor: Constant.SEPLINECOLOR,
        borderBottomWidth: StyleSheet.hairlineWidth
    },
    city: {
        flexGrow: 1,
        backgroundColor: '#fff',
        height: Platform.OS === 'ios' ? 35 : 45,
        paddingLeft: 10,
        justifyContent: 'center',
        borderRightColor: Constant.SEPLINECOLOR,
        borderRightWidth: StyleSheet.hairlineWidth
    },
    textSmall:{
        fontSize:Constant.FONT_SIZE_24,
        color:Constant.TEXT_COLOR_6
    }
}